const Wxmlify = require("../components/wxmlify/wxmlify");

var app = getApp();

Page({
  data: {
    relatedGoods: [],
    isTapCart:false,
    bIntegral:false,//判断是不是积分商城
    userInfoSHow: false,
    nTodayCount: 0, //今日访问总数
    bServicer: false, //是否是店主
    nSwiperCurrent: 0, //swiper
    bShowTopFlag: false,
    nScrollHeight: 500, //屏幕高度
    //  qrCode:'',//二维码
    canvasHeight: 500, //生成的图片高度
    canvasWidth: 300,
    drowFlag: false, //开始画图
    fee: 0, //运费
    fullFee: 0, //满多少钱免运费
    returnFlag: false, //商品一经售出概不退换
    returnedDay: "0", //退货
    exchangeDay: "0", //换货哦
    winHeight: "",
    id: "",
    goodsInfo: {},
    attribute: [], //已选择的规格型号
    specificationList: [], //规格型号
    number: 1,
    checkedSpecText: "请选择规格数量",
    checkedSpecId: "", //选中的id
    openAttr: false,
    show_share: false,
    maskHidden: false,
    scene: [], //分享参数
    currentSwiperIndex: 0, //当前轮播图片的索引
    ipx: false,
    pingjList: null
  },

  showEavluateList(e) {
    let obj = e.currentTarget.dataset.obj;
    wx.navigateTo({
      url: "../evaluateList/index?obj=" + JSON.stringify(obj)
    });
  },

  onShareAppMessage: function() {
    //获取分享者的ID
    let shareUrl = "/pages/loading/index?sceneT=" + this.data.scene.join("_");
    console.log("生产的分享链接", shareUrl);

    return {
      title: this.data.goodsInfo.skuName,
      imageUrl: this.data.goodsInfo.photos[0].photoUrl,
      path: shareUrl
    };
  },
  
  //获取产品信息
  getGoodsInfo: function() {
    // skuDetail({
    //   skuId: this.data.id
    // }).then(({ data }) => {
    //   if (data.success) {
    //     this.setData({
    //       goodsInfo: data.data,
    //     });
    //     var wxmlify = new Wxmlify(data.data.info, this, {});
    //     this.setRuleVlues();
    //   }
    // });
  },

  //  获取商品的退换货规则
  getGoodsReturnInfo() {
    const that = this;
    // getReturnBySkuId({
    //   skuId: that.data.id
    // }).then(({ data }) => {
    //   if (data.success) {
    //     that.setData({
    //       exchangeDay: data.data.exchangeDay,
    //       returnedDay: data.data.returnedDay
    //     });
    //     // 不支持退换货
    //     if (!data.data.exchangeDay && !data.data.returnedDay) {
    //       that.setData({
    //         returnFlag: true
    //       });
    //     } else {
    //       that.setData({
    //         returnFlag: false
    //       });
    //     }
    //   }
    // });
  },
  //  获取店铺的运费信息（全店通用）
  // getGoodsFreightInfo() {
  //   const that = this;
  //   getFreight().then(({ data }) => {
  //     if (data.success) {
  //       that.setData({
  //         fee: data.data.fee,
  //         fullFee: data.data.fullFee
  //       });
  //     }
  //   });
  // },
  //设置规格型号
  setRuleVlues: function() {
    if (this.data.openAttr) {
      return false;
    }
    let that = this;
    let selText = []; //选中的名称
    let productSelObj = []; //选中的规格型号
    let checkedSpecIdT = []; //选中的id
    let ruleValues = this.getRuleTemp();

    let rulueNameList = [];
    //获取到规格的行名称
    ruleValues.forEach((item, index) => {
      let nameCountT = -1;
      //已选择的
      // debugger
      if (item.skuIds.indexOf(that.data.goodsInfo.skuId) > -1) {
        selText.push(item.saleValue);
        checkedSpecIdT.push(item.valueId);
        productSelObj.push(item);
        item["checked"] = true;
      } else {
        item["checked"] = false;
      }
      //把规格分类
      if (item.skuIds.length > 0) {
        rulueNameList.forEach((itemR, indexR) => {
          if (itemR.name == item.ruleName) {
            nameCountT = indexR;
          }
        });
        if (nameCountT == -1) {
          const itemTemp = {
            name: item.ruleName,
            list: []
          };
          itemTemp.list.push(item);
          rulueNameList.push(itemTemp);
        } else {
          rulueNameList[nameCountT].list.push(item);
        }
      }
    });
    that.setData({
      attribute: productSelObj,
      specificationList: rulueNameList,
      checkedSpecText: selText.join(","),
      checkedSpecId: checkedSpecIdT.join("_")
    });
  },
  switchAttrPop: function(e) {
    this.setData({
      isTapCart: e.currentTarget.dataset['flag']
    })
    
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      });
    }
  },
  //选择规格型号
  clickSkuValue: function(event) {
    let that = this;
    let specNameId = event.currentTarget.dataset.nameId; //选择的父规格名称
    let specValueId = event.currentTarget.dataset.valueId; //选择的子规格id
    let indexP = event.currentTarget.dataset.indexP; //父规格所在的位置
    let index = event.currentTarget.dataset.index; //子规格所在的位置
    let checked = event.currentTarget.dataset.checked; //当前是否是选中
    //获取选中项的所有id
    let selSkuIdsT = [];

    let specificationListTemp = [];
    let selText = []; //选中的名称
    let productSelObj = []; //选中的规格型号
    let checkedSpecIdT = []; //选中的规格id
    var skuIdsSeled = [];
    let valueIdTemp = [];
    if (checked) {
      //点击之前是选中状态  认为是取消选中

      that.data.attribute.forEach((item, index) => {
        if (specValueId != item.valueId) {
          selSkuIdsT = selSkuIdsT.concat(item.skuIds);
        }
      });
    } else {
      let tempJson = that.data.specificationList[indexP].list[index].skuIds;

      selSkuIdsT = selSkuIdsT.concat(tempJson);

      that.data.attribute.forEach((item, index) => {
        if (specNameId != item.ruleName) {
          const intersects = item.skuIds.filter(x => tempJson.indexOf(x) > -1);

          if (intersects.length > 0) {
            selSkuIdsT = selSkuIdsT.concat(item.skuIds);
          } else {
            valueIdTemp.push(item.valueId);
          }
        } else {
          valueIdTemp.push(item.valueId);
        }
      });
    }
    // console.log(selSkuIdsT)
    selSkuIdsT = new Set(selSkuIdsT); //去重
    // console.log(selSkuIdsT)
    that.data.specificationList.forEach(item => {
      let specificationListChildTemp = [];
      item.list.forEach(itemList => {
        //当前点击的 取反处理
        if (specValueId == itemList.valueId) {
          itemList.checked = !checked;
        }

        //点击的不是已经选中的项 需要把所在的行的选中项剔除掉
        if (valueIdTemp.indexOf(itemList.valueId) > -1) {
          itemList.checked = false;
        }

        //可点击的处理
        let intersect = itemList.skuIds.filter(x => selSkuIdsT.has(x));
        if (intersect.length > 0) {
          itemList["isSelect"] = true;
        } else {
          itemList["isSelect"] = false;
        }

        //已经选中的处理
        if (itemList.checked) {
          selText.push(itemList.saleValue); //选中的名称
          productSelObj.push(itemList); //选中的规格型号

          checkedSpecIdT.push(itemList.valueId); //选中的id

          skuIdsSeled = skuIdsSeled.concat(itemList.skuIds);
        }
        specificationListChildTemp.push(itemList);
      });
      
      item.list = specificationListChildTemp;
      specificationListTemp.push(item);
    });

    that.setData({
      attribute: productSelObj,
      specificationList: specificationListTemp,
      checkedSpecText: selText.join(","),
      checkedSpecId: checkedSpecIdT.join("_")
    });

    //判断是否可以点击  当选择的属性 和总的属性相等的时候 就是  全部的规格都选择的 可以加载数据
    if (that.data.specificationList.length == that.data.attribute.length) {
    // if(true) {
      //  console.log(skuIdsSeled)
      var result = skuIdsSeled.reduce(
        (p, n) => (
          p[n]++ || (p[n] = 1),
          (p.max = p.max >= p[n] ? p.max : p[n]),
          (p.key = p.max > p[n] ? p.key : n),
          p
        ),
        {}
      );
      that.setData({
        id: result.key
      });
      that.getGoodsInfo();
    }
  },
  onCloseUserInfo() {
    this.setData({
      userInfoSHow: false
    });
  },
  // 获取访问数量
  getViews() {
    let _myData = {
      pageStart: 1,
      pageSize: 10,
      skuId: this.data.id,
      shopId: app.globalData.userInfo.shopId,
      type: 2 //查询类型（1，店铺访问，2，商品访问，3，加入购物车，4下单）
    };
    statisticsBase(_myData).then(({ data }) => {
      const { success, bizMessage, data: myData } = data;
      if (success) {
        this.handleUserData(myData.list);
      } else {
        if (!!!bizMessage) return;
        wx.showToast({
          title: bizMessage,
          icon: "none"
        });
      }
    });
  },

  // 处理用户数据
  handleUserData(list) {
    if (!!!list.length) return;
    let _list = list.slice(-10);
    let _flag = 0;
    _list.forEach(item => {
      if (time.myFormatTime(new Date()) == item.date.substring(4)) {
        _flag += 1;
        this.setData({
          nTodayCount: item.num
        });
      }
    });
    if (_flag == 0) {
      this.setData({
        nTodayCount: 0
      });
    }
    //  console.log(this.data.nTodayCount)
  },
  onLoad: function(options) {
    //  获取屏幕高度，用来返回顶部
    debugger
    this.getDeviceInfo();
    //  console.log(111,options);
    //改变小程序头部标题
    wx.setNavigationBarTitle({
      title: "商品详情"
    });
    // 页面初始化 options为页面跳转所带来的参数
    this.setData(
      {
        id: options.id,
        identity: app.globalData.userInfo.identity,
        bServicer: app.globalData.userInfo.identity == 1 ? true : false
      },
      () => {
        if (app.globalData.userInfo.identity == 1) this.getViews();
      }
    );
    wx.setStorageSync("shopLogo", app.globalData.userInfo.shopLogo);
    var that = this;
    this.getGoodsInfo(); //商品详情
    this.getGoodsReturnInfo(); //退换货规则
    // this.getGoodsFreightInfo(); //运费信息
    //分享者信息  如果分享者ID不存在
    if (
      !app.globalData.userInfo.personnelId ||
      app.globalData.userInfo.personnelId == ""
    ) {
      // getloginOnUser().then(({ data }) => {
      //   const scene = [];
      //   scene.push(app.globalData.userInfo.shopId);
      //   scene.push(data.data.personnelId);
      //   scene.push(that.data.id);

      //   this.setData({
      //     scene: scene
      //   });
      // });
    } else {
      const scene = [];
      scene.push(app.globalData.userInfo.shopId);
      scene.push(app.globalData.userInfo.personnelId);
      scene.push(that.data.id);
      this.setData({
        scene: scene
      });
    }
    // 获取canvas高度和宽度
    const res = wx.getSystemInfoSync();
    this.setData({
      canvasHeight: res.windowWidth + 50,
      canvasWidth: res.windowWidth - 50
    });

    //购物车数量
    // getCartNums().then(({ data }) => {
    //   if (data.success) {
    //     that.setData({
    //       cartGoodsCount: data.data
    //     });
    //   }
    // });

    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 100;

        that.setData({
          winHeight: calc
        });
      }
    });

    // 相同分类下的其他商品
    // const skuparams = {
    //   pageStart: 1,
    //   pageSize: 5,
    //   categoryId: 426
    // };
    
    //推荐商品
    // skuList(skuparams).then(({ data }) => {
    //   if (data.success) {
    //     that.setData({
    //       relatedGoods: data.data.list
    //     });
    //   }
    // });
    
  },

  onReady: function() {
    // 页面渲染完成
  },
  onShow: function() {
    // 页面显示
    this.setData({
      ipx: app.globalData.ipx,
      show_share: false
    });
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  //跳转首页
  goUrl: function() {
    wx.switchTab({
      url: "../homeIndex/index"
    });
  },
  //关闭操作
  closeAttrOrCollect: function() {
    if (this.data.openAttr) {
      this.setData({
        openAttr: false
      });
    }
  },
  //打开购物车
  openCartPage: function() {
    wx.switchTab({
      url: "../cartIndex/index"
    });
  },

  /**
   * 直接购买
   */
  buyGoods: function() {
    // if (app.globalData.userInfo.identity == 1) {
    //   wx.showToast({
    //     title: "店主不可以购买自己店铺的商品",
    //     duration: 1000,
    //     icon: "none"
    //   });
    //   return false;
    // }

    if (!this.data.goodsInfo.quantity) {
      wx.showToast({
        title: "卖光啦",
        duration: 1000,
        icon: "none"
      });
      return;
    }
    if (this.data.goodsInfo.status == 2) {
      wx.showToast({
        title: "已下架",
        duration: 1000,
        icon: "none"
      });
      return;
    }
    var that = this;
    //提示选择完整规格
    //  console.log(that.data.specificationList.length != that.data.attribute.length)
    // if (that.data.specificationList.length != that.data.attribute.length) {
    //   wx.showToast({
    //     title: '请选择规格',
    //     mask: true
    //   });
    //   return false;
    // }

    //验证库存

    if (that.data.number < 1) {
      wx.showToast({
        icon: "none",
        title: "库存不足",
        mask: true
      });
      return false;
    }

    // 直接购买商品 产品数量  产品id

    wx.navigateTo({
      url:
        "../home/pay/index?skuIds=" +
        that.data.id +
        "$" +
        that.data.number +
        "&isBuy=true"
    });
  },

  /**
   * 添加到购物车
   */
  addToCart: function() {
    // if (app.globalData.userInfo.identity == 1) {
    //   wx.showToast({
    //     title: "店主不可以购买自己店铺的商品",
    //     duration: 1000,
    //     icon: "none"
    //   });
    //   return false;
    // }
    
    if (!this.data.goodsInfo.quantity) {
      wx.showToast({
        title: "卖光啦",
        duration: 1000,
        icon: "none"
      });
      return;
    }
    if (this.data.goodsInfo.status == 2) {
      wx.showToast({
        title: "已下架",
        duration: 1000,
        icon: "none"
      });
      return;
    }
    var that = this;
    const myData = {
      skuId: that.data.id,
      num: that.data.number
    };
    addToCart(myData).then(({ data }) => {
      if (data.success) {
        that.setData({
          cartGoodsCount: that.data.cartGoodsCount + that.data.number
        });
        wx.showToast({
          title: "加车成功~",
          duration: 800
        });
        that.setData({
          openAttr: false
        });
      } else {
        wx.showToast({
          title: data.bizMessage,
          icon: "none"
        });
      }
    });
  },
  //减
  cutNumber: function() {
    this.setData({
      number: this.data.number - 1 > 1 ? this.data.number - 1 : 1
    });
  },
  //加
  addNumber: function() {
    this.setData({
      number: this.data.number + 1
    });
  },

  //分享朋友圈 查看保存图片
  user_share1: function() {
    this.setData({
      show_share: false
    });

    wx.showLoading({
      title: "图片生成中..."
    });
    //this.data.scene[2] skuId
    ImgErToFile({
      scene: this.data.scene[2],
      page: "pages/loading/index"
    })
      .then(res => {
        wx.hideLoading();
        const _base64 = wx.arrayBufferToBase64(res.data);
        let base64 = "data:image/jpeg;base64," + _base64;
        base64src(base64)
          .then(r => {
            return r;
          })
          .then(r => {
            let imgUrl = this.data.goodsInfo.photos[
              this.data.currentSwiperIndex
            ].photoUrl;
            if (imgUrl.indexOf("http://media.avicyt.com/") > -1) {
              imgUrl = imgUrl.replace(
                "http://media.avicyt.com/",
                "https://xcx.ruiysoft.com/microshop/qnimg/"
              );
            }
            const goods = {
              name: this.data.goodsInfo.skuName,
              price: this.data.goodsInfo.unitPrice,
              photographUrl: imgUrl,
              describe: this.data.goodsInfo.skuName,
              erwmData: r
            };
            this.setData({
              drowFlag: true
            });

            const obj = {
              canvasHeight: this.data.canvasHeight, //生成的图片高度
              canvasWidth: this.data.canvasWidth
            };

            // shareObj.setCanvasImg(goods, obj);
          });
      })
      .catch(() => {
        wx.hideLoading();
      });
  },
  //  分享
  user_share() {
    //  console.log(app.globalData);
    let imgUrl = this.data.goodsInfo.photos[this.data.currentSwiperIndex]
      .photoUrl;
    if (imgUrl.indexOf("http://media.avicyt.com/") > -1) {
      imgUrl = imgUrl.replace(
        "http://media.avicyt.com/",
        "https://xcx.ruiysoft.com/microshop/qnimg/"
      );
    }
    
    const myData = {
      name: this.data.goodsInfo.skuName,
      price: this.data.goodsInfo.unitPrice,
      photographUrl: imgUrl,
      scene: this.data.scene[2],
      page: "pages/loading/index"
    };

    // shareObj.getUserInfo(app);
    wx.navigateTo({
      url: `../share/share?${qs.stringify(myData)}`
    });
  },
  //  客服消息
  goChat() {
    //  要获取用户授权
    if (app.globalData.userInfo.avatarUrl) {
      // skuIds：商品id，type商品，name客户
      // const myData = {
      //   skuIds: this.data.id,
      //   type: "product",
      //   name: "customer",
      //   listPrice: this.data.goodsInfo.listPrice,
      //   photo: this.data.goodsInfo.photos[0].photoUrl,
      //   quantity: this.data.goodsInfo.quantity,
      //   skuId: this.data.id,
      //   skuName: this.data.goodsInfo.skuName,
      //   status: this.data.goodsInfo.status,
      //   unitPrice: this.data.goodsInfo.unitPrice
      // };
      wx.navigateTo({
        // url: `../chat/chat?${qs.stringify(myData)}` //客户入口
        url: `../chat/chat` //客户入口
      });
      return false;
    } else {
    }
    this.setData({
      userInfoSHow: true
    });
  },
  //用户授权
  getUserInfo(e) {
    this.setData({
      userInfoSHow: false
    });
    if (e.detail.errMsg.indexOf("fail") > -1) {
      return false;
    }
    wxLoginUserInfo().then(res => {
      if (res.flag) {
        //授权成功  获取用户信息
        wx.setStorageSync("userInfo", res.getUserInfo.userInfo);
        this.setData({
          userInfo: res.getUserInfo.userInfo
        });
        app.globalData.userInfo.avatarUrl = res.getUserInfo.userInfo.avatarUrl;
        app.globalData.userInfo.city = res.getUserInfo.userInfo.city;
        app.globalData.userInfo.country = res.getUserInfo.userInfo.country;
        app.globalData.userInfo.gender = res.getUserInfo.userInfo.gender;
        app.globalData.userInfo.language = res.getUserInfo.userInfo.language;
        app.globalData.userInfo.nickName = res.getUserInfo.userInfo.nickName;
        app.globalData.userInfo.province = res.getUserInfo.userInfo.province;
        app.globalData.userInfo.userCode = res.loginInfo.code;
      }
    });
  },
  //  海报保存到本地
  saveImg() {
    const obj = {
      canvasHeight: this.data.canvasHeight, //生成的图片高度
      canvasWidth: this.data.canvasWidth
    };
    // shareObj.save2album(obj).then(() => {
    //   this.hideImg();
    // });
  },
  //  海报隐藏
  hideImg() {
    this.setData({
      drowFlag: false
    });
  },
  // 弹窗
  onClose: function(e) {
    this.setData({
      show_share: e.currentTarget.dataset.status == 1 ? true : false
    });
  },
  //点击保存到相册
  baocun: function() {
    var that = this;

    wx.getSetting({
      success(res) {
        if (!res.authSetting["scope.writePhotosAlbum"]) {
          wx.authorize({
            scope: "scope.writePhotosAlbum",
            success() {
              //  console.log('授权成功')
            },
            fail: function(res) {
              wx.openSetting({
                success: res => {
                  res.authSetting = {
                    "scope.userInfo": true,
                    "scope.userLocation": true,
                    "scope.writePhotosAlbum": true
                  };
                }
              });
            }
          });
        } else {
        }
      }
    });

    wx.downloadFile({
      url: that.data.imagePath,
      success: function(res) {
        var tempFilePath = res.tempFilePath;

        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success(res) {
            wx.showModal({
              content: "图片已保存到相册，赶紧晒一下吧~",
              showCancel: false,
              confirmText: "好的",
              confirmColor: "#333",
              confirmColor: "#0080FF",
              cancelColor: "#3d3d3d",
              success: function(res) {
                if (res.confirm) {
                  /* 该隐藏的隐藏 */
                  that.setData({
                    maskHidden: false
                  });
                }
              },
              fail: function(res) {}
            });
          }
        });
      }
    });
  },
  //关闭分享
  close_share: function(e) {
    var that = this;
    that.setData({
      maskHidden: false
    });
  },
  swiperChange: function(e) {
    if (e.detail.source == "touch") {
      this.setData({
        currentSwiperIndex: e.detail.current
      });
      
      if (e.detail.current >= this.data.goodsInfo.photos.length - 1) {
        setTimeout(function () {
          wx.pageScrollTo({
            scrollTop: 840
          });

        }, 2000);
       
      }
    }
  },
  //模拟规格型号
  getRuleTemp: function() {
    let rulesListTemp = [];
    let skuIdTemp = this.data.goodsInfo.skuId;
    if (
      this.data.goodsInfo.RuleValues &&
      this.data.goodsInfo.RuleValues.length > 0
    ) {
      this.data.goodsInfo.RuleValues.forEach(item => {
        rulesListTemp.push({
          valueId: item.id,
          saleValue: item.value,
          isSelect: 0,
          ruleName: item.ruleName,
          skuIds: item.skus
        });
      });
    }
    return rulesListTemp;
  },
  //下拉刷新
  onPullDownRefresh() {
    wx.stopPullDownRefresh(); //停止刷新
  },
  onPageScroll: function(e) {
    this.setData({
      bShowTopFlag: e.scrollTop > this.data.nScrollHeight ? true : false
    });
  },
  // 获取设备信息
  getDeviceInfo() {
    wx.getSystemInfo({
      success: ({ windowHeight }) => {
        this.setData({
          nScrollHeight: windowHeight
        });
      }
    });
  },
  //  返回顶部
  hanldeTop() {
    wx.pageScrollTo({
      scrollTop: 0
    });
  }
});